package hnevc.com.netfoodchoosez;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class ShowFoodActivity extends AppCompatActivity {

    List<Food> mFoodList; //食物列表
    //ListView mListView;
    RecyclerView mRecyclerView;
    MyBaseAdapter mAdapter; //适配器
    ImageButton mIbQuery;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show_food);
        initView();
        //如果有传递过来的数据则使用传递过来的数据，否则去往上下载数据
        if (getIntent().getSerializableExtra("foodList")!=null){
            mFoodList = (List<Food>) getIntent().getSerializableExtra("foodList");
            MyBaseAdapter adapter = new MyBaseAdapter();//创建适配器对象
            mListView.setAdapter(adapter);//绑定适配器到Listview
        }else {
            initData();
        }
        //initData();
        initEvent();
    }

    private void initEvent() {

        mIbQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(ShowFoodActivity.this,SettingActivity.class);
                startActivity(intent);

            }
        });
    }

    private void initView() {

        //mListView = (ListView) findViewById(R.id.id_lv_food_list);
        mRecyclerView = (RecyclerView) findViewById(R.id.id_rv_food_list);
        mIbQuery = (ImageButton) findViewById(R.id.id_ib_query);
    }

    /**
     * 初始化数据，用来获取食物列表的数据
     */
    private void initData() {
        //TODO 访问网络获取数据，填充mFoodList,然后创建数据适配器，更新界面

        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO 访问网络获取数据
                //1 创建请求对象
                Request request = new Request.Builder()
                        .url("http://"+getResources().getString(R.string.ServerIp)+":8080/RestaurantServer/Food/getFoods")
                        .get()
                        .build();
                //2 创建客户端发送请求

                OkHttpClient client = new OkHttpClient.Builder()
                        .cookieJar(new MyCookieJar())
                        .build();

                try {
                    Response response = client.newCall(request).execute();
                    String data = response.body().string();
                    Log.e("TAG", "run: "+data );
                    // TODO 解析data，将其转换为mFoodList
                    Gson gson = new Gson();//构建gson对象
                    mFoodList = gson.fromJson(data ,new TypeToken<List<Food>>(){}.getType());//解析json数组
                    //mFoodList = gson.fromJson(data ,new TypeToken<List<Food>>(){}.getType());

                    //TODO 创建数据适配器，更新界面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            MyBaseAdapter adapter = new MyBaseAdapter();//创建适配器对象

                            mRecyclerView.setAdapter(adapter);//绑定适配器到Listview
                        }
                    });

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    }).start();

}

    //TODO 根据数据mFoodList，自定义数据适配器
    class MyBaseAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mFoodList.size();
        }

        @Override
        public Object getItem(int i) {
            return mFoodList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return mFoodList.get(i).getFoodId();
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            view = View.inflate(
                    ShowFoodActivity.this,
                    R.layout.food_list_item,
                    null);

            // TODO 获取当前位置对应的数据
            final Food food = mFoodList.get(i);
            TextView tvFoodName = (TextView) view.findViewById(R.id.id_tv_foodName);
            tvFoodName.setText(food.getFoodName());

            // TODO 显示图片,Picasso库
                //1、获取显示图片的控件
            ImageView ivPic = (ImageView) view.findViewById(R.id.id_iv_foodPic);
                //2、获取图片路径
            String imageurl = "http://"+getResources().getString(R.string.ServerIp)+":8080/RestaurantServer/uploadFoodImage/"
                    +food.getFoodPic();
                //3、利用picasso加载显示图片到ivpic
            Picasso.with(ShowFoodActivity.this)
                    .load(imageurl)
                    .into(ivPic);

            TextView tvFoodDesc = (TextView) view.findViewById(R.id.id_tv_foodDesc);
            tvFoodDesc.setText(food .getFoodDesc());

            //TODO 设置ListViewItem的点击事件
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //TODO 跳转到FoodDetailActivity
                    Intent intent = new Intent();
                    intent.setClass(ShowFoodActivity.this,FoodDetailActivity.class);

                    //传递参数id
                    intent.putExtra("foodID",food.getFoodId());
                    startActivity(intent);

                }
            });
            return view;
        }
    }
}
